package com.y2.authprj.mvc.interceptor.auth;

import java.lang.reflect.Method;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.gdglc.spring.annotations.AuthValidate;
import com.gdglc.spring.biz.auth.FunctionauthorityBiz;
import com.gdglc.spring.biz.impl.auth.FunctionauthorityBizImpl;
import com.y2.authprj.bean.auth.model.AuthorCheck;
import com.y2.authprj.bean.auth.model.StaffInfo;

public class LoginInterceptor implements HandlerInterceptor{
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		System.out.println("==============进入LoginInterceptor拦截器=============");
		boolean flag=false;
		HandlerMethod handlerMethod = (HandlerMethod)handler;
		//获取执行方法
		Method method = handlerMethod.getMethod();
		System.out.println(method);
		AuthValidate authValidate = method.getAnnotation(com.gdglc.spring.annotations.AuthValidate.class);
		if(authValidate!=null){
			AuthorCheck check = new AuthorCheck();
			String authName = authValidate.value();
			String authNoStr = check.getFunctionIdByName(authName);
			int authNo = 0;
			if(authNoStr!=null){
				authNo = Integer.parseInt(authNoStr);
			}
			
			StaffInfo staffInfo = (StaffInfo)request.getSession().getAttribute("staffInfo");
			if(staffInfo!=null){
				List<String> functionauthorityIdList=check.getFunctionauthorityIdByStaffId(String.valueOf(staffInfo.getStaffId()));
				if(functionauthorityIdList!=null){
					for(String id:functionauthorityIdList){
						if(id.equals(String.valueOf(authNo))){
							flag = true;
						}
					}
				}
			}
		}else if(authValidate==null){
			flag=true;
		}
		
		if(!flag){
			request.getRequestDispatcher("/authError.jsp").forward(request, response);
		}
		return flag;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("==============进入LoginInterceptor拦截器=============");
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		System.out.println("==============进入LoginInterceptor拦截器=============");
	}
}
